'use strict';
// 引入工具库
const utils = require('utility');

const Controller = require('egg').Controller;

class UserController extends Controller {
  // 添加用户(一定要先查再插入）
  async addUser() {
    const { ctx, app } = this;
    let { username, password, email, sex, phone,desc } = ctx.request.body;
    if (!username) return ctx.body = { success: false, info: '请填写用户名' };
    if (!password) return ctx.body = { success: false, info: '请填写密码' };
    if (!email) return ctx.body = { success: false, info: '请填写邮箱' };
    if (!phone) return ctx.body = { success: false, info: '请填写手机号码' };
    // if(!(/^1[3456789]\d{9}$/.test(phone))) return ctx.body = {success:false,info:'请填写正确的手机号码'}
    console.log(ctx.request.body);
    try {
      const _u = await ctx.model.User.findAll({
        where: {
          username,
          phone
        },raw:true // 增加raw:true会返回数据库原始的结果
      });

      // console.log('///',_u);

      if (_u[0]){
        ctx.body = { success: false, info: '用户已注册' };
        return
      }
      try {
        await ctx.model.User.create({
          username,
          password:utils.md5(password),
          email,
          sex,
          phone,
          desc,
          // Date.now()才是返回时间戳
          create_time: Date.now(),
          update_time: Date.now()
        });
        ctx.body = { success: 'true', info: '添加成功' };
      } catch (e) {
        ctx.body = { success: 'false', info: '添加失败' };
        console.log('eeee',e);
      }
    } catch (e) {
      ctx.body = { success: 'false', info: '用户不存在' };
    }


  }

  // 修改用户
  async editUser() {
    const {ctx} = this
    const {id,email,phone,desc} = ctx.request.body
    const updateObj = {}
    if(email) updateObj.email = email
    if(phone) updateObj.phone = phone
    if(desc) updateObj.desc = desc
    updateObj.update_time = Date.now() // 更新时间
    try{
      await ctx.model.User.update(updateObj,{
        where:{
          id
        }
      })
      ctx.body = { success: true, info: '修改用户成功' };
    }catch (e){
      ctx.body = { success: false, info: '修改用户失败' };
      console.log('error',e);
    }
  }

  // 删除用户
  async delUser(){
    const {ctx} =this
    const id = ctx.query.id
    try {
      await ctx.model.User.destroy({
        where:{
          id
        }
      })
      ctx.body = { success: true, info: '删除用户成功' }
    }catch (e){
      ctx.body = { success: false, info: '删除用户失败' }
      console.log('e',e);
    }

  }

  // 根据id查询用户
  async findOneUser(){
    const {ctx} = this
    const {id} = ctx.query
    try{
    const u =   await ctx.model.User.findOne({
        where:{
          id
        },raw:true
      })
      ctx.body = {success:true,info:'查询成功',data:u}
    }catch (e){
      ctx.body = {success:false,info:'查询失败'}
    }

  }

  // 查询全部用户(分页查询)
  async findAllUser(){
    const {app,ctx} = this
    const {Op} = app.Sequelize
    // pagenum:当前页 pagesize:每一页显示的条数
    let {pagenum,pagesize,queryInfo} = ctx.query
    let where = {}
    if(queryInfo) where.desc = {[Op.like]:'%'+queryInfo+'%'}
    let offset = (pagenum-1) * pagesize
    try{
    const res = await ctx.model.User.findAndCountAll({
      where:where,
      // 控制查询字段
      // attributes:['id','username'],
      // limit为限制的条数
        limit:parseInt(pagesize),
        offset:offset,
        order:[['id','DESC']],
        raw:true
      })
      ctx.body = {success:true,info:'查询成功',data:{result:res.rows,pagenum,pagesize,total:res.count}}
    }catch (e){
      ctx.body = {success:false,info:'查询失败'}
      console.log('errrr',e);
    }
  }

  // 查询全部用户(模糊查询)
  async findUsers(){
    const {app,ctx} = this
    const { Op } = app.Sequelize
    const {desc,phone} = ctx.request.body
    const where = {}
    if(desc) where.desc = {[Op.like]:'%'+desc+'%'}
    if(phone) where.desc = {[Op.like]:'%'+phone+'%'}

    try {
    const res =  await ctx.model.User.findAll({
        where:where,
        raw:true,
        order:[['id','DESC']],
      })
      ctx.body = { success: true, info: '查询成功', data: res };
    }catch (e){
      ctx.body = {success:false,info:'查询失败'}
      console.log('xxx',e);
    }
  }



}

module.exports = UserController;
